package com.news.reader;

import java.io.IOException;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.commons.net.nntp.NNTPClient;
import org.apache.commons.net.nntp.NewsgroupInfo;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class GroupList extends ListActivity  {
	List<String> groups = new ArrayList<String>();
	private NNTPClient client;
	String newsgroup;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Bundle extras = getIntent().getExtras();
        if(extras !=null)
        {
        	try {
        		ProgressDialog MyDialog = ProgressDialog.show(GroupList.this, "Loading Group" , " Loading. Please wait ... ", true);
        		client = new NNTPClient();
        		newsgroup = extras.getString("newsgroup");
				client.connect(newsgroup, 119);
	        	NewsgroupInfo[] list = client.listNewsgroups();
	            if (list != null){
	                for (int i = 0; i < list.length; i++){
	                    groups.add(list[i].getNewsgroup());
	                }
	            }
	            Collections.sort(groups);
	            setListAdapter(new ArrayAdapter<String>(this, R.layout.row, R.id.label, groups));
	            MyDialog.dismiss();
			} catch (SocketException e) {
				e.printStackTrace();
			} catch (IOException e) {
				//Toast t = Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG);
				//t.show();
				e.printStackTrace();
			} finally {
	            try {
	                if (client.isConnected())
	                    client.disconnect();
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
			}
        }
    }
    
    public void onListItemClick(ListView parent, View v, int position, long id) {
    	launchThreadList(this.newsgroup, this.groups.get(position));
    }
    
    protected void launchThreadList(String newsgroup, String group) {
        Intent i = new Intent(this, ThreadList.class);
        i.putExtra("group", group);
        i.putExtra("newsgroup", newsgroup);
		startActivity(i);
    }
}
